package com.yhsoft.bill.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yhsoft.bill.controller.request.SalerYszkInVo;
import com.yhsoft.bill.controller.response.*;
import com.yhsoft.bill.mapper.BillReportMapper;
import com.yhsoft.bill.service.BillReportService;
import com.yhsoft.bill.service.ISalerYszkService;
import com.yhsoft.common.service.TokenService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class BillReportServiceImpl implements BillReportService {
    @Autowired
    BillReportMapper billReportMapper;

    @Resource
    private ISalerYszkService iSalerYszkService;

    //预存款消耗日志报表导出
    @Override
    public void exportYckLog(HttpServletResponse response, Integer distributorId) throws IOException {
        try {
            List<SysYckLogOutVo> logData = billReportMapper.select(SysYckLogOutVo.class);
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("预存款消耗日志报表");
            //创立标题行
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"渠道商订单号", "供应商订单号", "商品名称", "商品类型",
                    "渠道商名称", "渠道商主体"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            //填充行数据
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (int i = 0; i < logData.size(); i++) {
                SysYckLogOutVo sysYckLogOutVo = logData.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(sysYckLogOutVo.getOrderNo());
                row.createCell(1).setCellValue(sysYckLogOutVo.getVenderOrderNo());
                row.createCell(2).setCellValue(sysYckLogOutVo.getGoodsName());
                row.createCell(3).setCellValue(sysYckLogOutVo.getGoodsType());
//                row.createCell(4).setCellValue(sysYckLogOutVo.getSkuName());
//                row.createCell(5).setCellValue(sysYckLogOutVo.getSkuQuantity());
//                row.createCell(6).setCellValue(sysYckLogOutVo.getGoodsPrice().doubleValue());
//                row.createCell(7).setCellValue(sysYckLogOutVo.getTotlePrice().doubleValue());
//                Cell paytimeCell = row.createCell(8);
//                paytimeCell.setCellValue(sysYckLogOutVo.getPayTime().format(formatter));
//                CellStyle dateCellStyle = workbook.createCellStyle();
//                dateCellStyle.setDataFormat(workbook.getCreationHelper()
//                        .createDataFormat()
//                        .getFormat("yyyy-MM-dd"));
//                paytimeCell.setCellStyle(dateCellStyle);
                row.createCell(4).setCellValue(sysYckLogOutVo.getCompanyName());
                row.createCell(5).setCellValue(sysYckLogOutVo.getCompanyZt());
            }
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("预存款消耗日志报表", "UTF-8") + ".xlsx");
            //保存文件
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //关闭资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        System.out.println("导出文件成功！");
    }


    //应付款项报表导出
    @Override
    public void exportYszkMx(HttpServletResponse response, Integer distributorId) throws IOException {
        try {
            List<SysYszkMxOutVo> logData = billReportMapper.selectOut(SysYszkMxOutVo.class);
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("应付款项报表");
            //创立标题行
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"id", "经手人", "类型", "金额", "支付凭证Url", "入账时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            //填充行数据
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (int i = 0; i < logData.size(); i++) {
                SysYszkMxOutVo mxOutVo = logData.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(mxOutVo.getId());
                row.createCell(1).setCellValue(mxOutVo.getPayBy());
                row.createCell(2).setCellValue(mxOutVo.getType());
                row.createCell(3).setCellValue(mxOutVo.getPayAmount().doubleValue());
                row.createCell(4).setCellValue(mxOutVo.getVoucher());
                Cell payTimeCell = row.createCell(5);
                payTimeCell.setCellValue(mxOutVo.getPayTime().format(formatter));
                CellStyle DateCellStyle = workbook.createCellStyle();
                DateCellStyle.setDataFormat(workbook.getCreationHelper()
                        .createDataFormat()
                        .getFormat("yyyy-MM-dd"));
                payTimeCell.setCellStyle(DateCellStyle);
            }
            //调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("应付款项报表", "UTF-8") + ".xlsx");
            //保存Excel文件
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //关闭资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.println("导出文件成功！");
    }


    //对账明细表
    @Override
    public void exportDetail(HttpServletResponse response, Integer distributorId) throws IOException {
        try {
            List<SysYckLogOutVo> logData = billReportMapper.selectBu(SysYckLogOutVo.class);
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("对账明细表");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Row headerRow = sheet.createRow(1);
            String[] headers = {"渠道商订单号", "供应商订单号", "商品名称", "商品类型", "渠道商名称", "渠道商主体"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            for (int i = 0; i < logData.size(); i++) {
                SysYckLogOutVo log = logData.get(i);
                // 创建公司名称行
                Row companyRow = sheet.createRow(0);
                Cell companyCell = companyRow.createCell(0);
                companyCell.setCellValue(log.getCompanyZt());
                // 创建表行

                Row row = sheet.createRow(i + 2); // 数据行从第3行开始
                row.createCell(0).setCellValue(log.getOrderNo());
                row.createCell(1).setCellValue(log.getVenderOrderNo());
                row.createCell(2).setCellValue(log.getGoodsName());
                row.createCell(3).setCellValue(log.getGoodsType());
//                row.createCell(6).setCellValue(log.getGoodsPrice().doubleValue());
                row.createCell(4).setCellValue(log.getCompanyName());
                row.createCell(5).setCellValue(log.getCompanyZt());
            }
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("对账明细表", "UTF-8") + ".xlsx");
            //保存Excel文件
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //关闭资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("导出文件成功！");
    }


    //应收账款详情列表
    @Override
    public void ExportAccounts(HttpServletResponse response) throws IOException {
        try {
            List<SalerYszkMxOutVo> logData = billReportMapper.selectAu(SalerYszkMxOutVo.class);
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("应收账款详情报表");
            //创立标题行
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"id", "关联批次", "激活批次号", "应收金额", "生成时间", "入账金额", "支付凭证", "经手人"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (int i = 0; i < logData.size(); i++) {
                SalerYszkMxOutVo salerYszkMxOutVo = logData.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(salerYszkMxOutVo.getId());
                row.createCell(1).setCellValue(salerYszkMxOutVo.getFirstBatchNum());
                row.createCell(2).setCellValue(salerYszkMxOutVo.getSecondBantchNum());
                row.createCell(3).setCellValue(salerYszkMxOutVo.getYsAmount()
                        .doubleValue());
                //    row.createCell(5).setCellValue(salerYszkMxOutVo.getPayAmount().floatValue());
                Cell createTimeCell = row.createCell(4);
                createTimeCell.setCellValue(salerYszkMxOutVo.getCreateTime().format(formatter));
                CellStyle DateCellStyle = workbook.createCellStyle();
                DateCellStyle.setDataFormat(workbook.getCreationHelper()
                        .createDataFormat()
                        .getFormat("yyyy-MM-dd"));
                createTimeCell.setCellStyle(DateCellStyle);
                row.createCell(6).setCellValue(salerYszkMxOutVo.getVoucher());
                row.createCell(7).setCellValue(salerYszkMxOutVo.getPayBy());
//                Cell payTimeCell = row.createCell(8);
//                payTimeCell.setCellValue(salerYszkMxOutVo.getPayTime().format(formatter));
//                CellStyle DateCellStyle1 = workbook.createCellStyle();
//                DateCellStyle.setDataFormat(workbook.getCreationHelper()
//                        .createDataFormat()
//                        .getFormat("yyyy-MM-dd "));
//                payTimeCell.setCellStyle(DateCellStyle1);
            }
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("应收账款详情", "UTF-8") + ".xlsx");
            //保存Excel文件
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //关闭资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("导出文件成功!");
    }


    //应收账款报表
    @Override
    public void ExportReceivable(HttpServletResponse response) throws IOException {
        try {
            IPage<SalerYszkOutVo> iPage = iSalerYszkService.getYszkList(new SalerYszkInVo(), 1L, 10000000L);
            List<SalerYszkOutVo> logData = iPage.getRecords();
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("应收账款详情报表");
            //创立标题行
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"id", "下游企业名称", "总计应收账款", "已收账款", "未结款", "创建时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < logData.size(); i++) {
                SalerYszkOutVo salerYszkOutVo = logData.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(salerYszkOutVo.getId());
                row.createCell(1).setCellValue(salerYszkOutVo.getCustomerName());
                row.createCell(2).setCellValue(salerYszkOutVo.getTotalYsAmount().doubleValue());
                row.createCell(3).setCellValue(salerYszkOutVo.getTotalPayAmount().doubleValue());
                row.createCell(4).setCellValue(salerYszkOutVo.getNeedPayAmount().doubleValue());
                Cell createTimeCell = row.createCell(5);
                createTimeCell.setCellValue(salerYszkOutVo.getCreateTime().format(formatter));
                CellStyle DateCellStyle = workbook.createCellStyle();
                DateCellStyle.setDataFormat(workbook.getCreationHelper()
                        .createDataFormat()
                        .getFormat("yyyy-MM-dd"));
                createTimeCell.setCellStyle(DateCellStyle);
            }
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("应收账款报表", "UTF-8") + ".xlsx");
            //保存Excel文件
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //关闭资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("导出文件成功!");
    }

    @Override
    public void ExportConsumption(HttpServletResponse response) throws IOException {
        try {
            Integer companyId = TokenService.getUserBytoken().getCompanyId();
            List<SalerXhLogOutVo> logData = billReportMapper.selectDu(SalerXhLogOutVo.class, companyId);
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("消耗日志报表");
            //创立标题行
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"渠道商订单号", "商品名称", "商品类型", "收货人", "手机号码",
                    "微信昵称", "支付时间", "快递公司", "快递单号", "渠道商名称", "渠道商主体"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < logData.size(); i++) {
                SalerXhLogOutVo salerXhLogOutVo = logData.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(salerXhLogOutVo.getOrderNo());
                row.createCell(1).setCellValue(salerXhLogOutVo.getGoodsName());
                row.createCell(2).setCellValue(getGoodsType(salerXhLogOutVo.getGoodsType()));
//                row.createCell(4).setCellValue(salerXhLogOutVo.getSkuQuantity());
//                row.createCell(5).setCellValue(salerXhLogOutVo.getGoodsPrice().doubleValue());
//                row.createCell(6).setCellValue(salerXhLogOutVo.getTotlePrice().doubleValue());
                row.createCell(3).setCellValue(salerXhLogOutVo.getName());
                row.createCell(4).setCellValue(salerXhLogOutVo.getMobile());
                row.createCell(5).setCellValue(salerXhLogOutVo.getNickName());
                if (salerXhLogOutVo.getPayTime() != null) {
                    row.createCell(6).setCellValue(formatter.format(salerXhLogOutVo.getPayTime()));
                } else {
                    row.createCell(6).setCellValue("");
                }
                row.createCell(7).setCellValue(salerXhLogOutVo.getExpressCompany());
                row.createCell(8).setCellValue(salerXhLogOutVo.getExpressNo());
                row.createCell(9).setCellValue(salerXhLogOutVo.getCompanyName());
                row.createCell(10).setCellValue(salerXhLogOutVo.getCompanyZt());
            }
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("消耗日志报表", "UTF-8") + ".xlsx");
            //保存Excel文件
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //关闭资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("导出文件成功!");
    }

    private String getGoodsType(String goodsType) {
        // 商品类型：1-电影，2-蛋糕，3-电子券，4-api电商，5-线下供应商
        switch (goodsType){
            case "1":
                return "电影";
            case "2":
                return "蛋糕";
            case "3":
                return "电子券";
            case "4":
                return "api电商";
            case "5":
                return "线下供应商";
            default:
                return "未知类型";
        }
    }


}


